# -*- coding: utf8 -*-
"""
用于全文搜索，比如产品搜索、mtu搜索
Ref: https://vinta.ws/code/using-elasticsearch-dsl-with-python.html

# TODO: 添加alias，好处是可以无缝切换，零停机时间。 Ref:http://es.xiaoleilu.com/070_Index_Mgmt/55_Aliases.html
"""

from elasticsearch_dsl import DocType, String, Boolean, Date
from elasticsearch_dsl.connections import connections
connections.create_connection(hosts=['192.168.1.198', ])


class ProductDoc(DocType):
    name = String(analyzer='ik')
    is_active = Boolean()
    published = Boolean()
    destination_id = String(index='not_analyzed')
    classify_id = String(index='not_analyzed')
    last_modified = Date()

    class Meta:
        index = 'sz_vacation'  # 加sz_前缀防止冲突
        doc_type = 'product'

    @classmethod
    def sync(cls, product):
        product_doc = ProductDoc(meta={'id': product.id})  # elasticsearch中的id跟mongodb的id一一对应
        product_doc.name = product.name
        product_doc.is_active = product.is_active
        product_doc.published = product.published
        product_doc.destination_id = str(product.destination.id)
        product_doc.classify_id = str(product.classify.id) if product.classify else ''
        product_doc.last_modified = product.last_modified
        product_doc.save()

    def save(self, *args, **kwargs):
        return super(ProductDoc, self).save(*args, **kwargs)

    # def get_model_obj(self):
    #     from app.models import Product
    #     return Product.objects.get(id=self.meta.id)

# to create mappings
ProductDoc.init()
